<?php

namespace frontend\modules\shop\controllers;

use backend\modules\business\models\BusinessPig;
use common\components\Upload;
use common\models\business\BusinessUser;
use common\models\business\BusinessVariety;
use common\models\shop\ShopCart;
use common\models\shop\ShopDispatch;
use common\models\shop\ShopExpress;
use common\models\shop\ShopGoods;
use common\models\shop\ShopOrder;
use common\models\shop\ShopOrderGoods;
use common\models\shop\ShopRaisingOrder;
use common\models\shop\ShopSinceAddress;
use common\models\shop\ShopUserAddress;
use common\models\sys\SysSetting;
use EasyWeChat\Payment\Order;
use frontend\controllers\BaseMobileController;
use yii\db\Exception;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\Controller;


/**
 * Class OrderController
 * @package frontend\modules\shop\controllers
 * 订单相关控制器
 */
class OrderController extends BaseMobileController
{


    /**
     * @return string
     * 确认订单页面
     */
    public function actionConfirm()
    {

        //取出配送方式
        $dispatchs = ShopDispatch::find()
            ->alias('s')
            ->select('s.id,s.dispatchname,s.firstprice as price,firstweight as weight,secondweight,secondprice')
            ->leftJoin(ShopExpress::tableName().' as se','s.express=se.id')
            ->asArray()
            ->indexBy('dispatchname')
            ->all();

        if($dispatchs){
            foreach ($dispatchs as $key => $row)
            {
                $dispatchs[$key]['selected'] = 1;
                break;
            }
        }else{
            $dispatchs = [];
        }


        //取出地址
        $addressid = \Yii::$app->request->get('addressid');
        if(!empty($addressid)){
            $parmsstr = 'id=:id';
            $params = [':id' => $addressid];
        }else{
            $parmsstr = 'userid=:userid and isdef=:isdef';
            $params = [':isdef' => 1,':userid'=>$this->user['userid']];
        }

        //取出收货地址
        $address = ShopUserAddress::find()
            ->select('id,province,city,county as area,address,tel as mobile,name as realname')
            ->where($parmsstr,$params)
            ->asArray()
            ->one();

        //取出自提地址
        $since = ShopSinceAddress::find()
            ->select('concat(`province`,`city`,`conty`,`area`) as address,remark,id')
            ->asArray()
            ->all();
        foreach ($since as $key => $row)
        {
            $since[0]['selected'] = 1;
        }


        //积分兑换金额比率
        $radio = SysSetting::getValue('scoretomoney');
        $user = BusinessUser::find()->select('score')->where('id=:id',[':id'=>$this->user['userid']])->asArray()->one();
        $reduce = ($user['score']*$radio);

        //取出最多可以使用的积分
        $maxscore = SysSetting::getValue('canusemax_score');
        if($reduce > $maxscore){
            $reduce = $maxscore;
            $user['score'] = intval($reduce/$radio);
        }
        $user['score'] = $user['score']?$user['score']:0;
        return $this->render('@template/mobile/confirm.html',[
            'delivery_list' => \GuzzleHttp\json_encode($dispatchs),
            'address' => \GuzzleHttp\json_encode($address),
            'since' => \GuzzleHttp\json_encode($since),
            'ziti' => $address,
            'reduce' => $reduce,
            'score' => $user['score']
        ]);
    }





    /**
     * 商品下单支付
     */
    public function actionPrePay()
    {
        $postdata = \Yii::$app->request->post();


        //取出购买的商品
        $allgoods = (new Query())->select('productprice,g.id,weight,g.total,g.title')
            ->from(ShopGoods::tableName().' as g')
            ->where(['g.id' => $postdata['goodsid']])
            ->all();


        if(!$allgoods){
            return $this->jsonMsg('商品不能为空');
        }

        // 计算商品价格和总重量
        $allweight = 0;
        $goodsprice = 0;
        sort($postdata['goodsid']);
        foreach ($allgoods as $key => $row)
        {
            if($row['total'] < $postdata['goodsnum'][$key]){
                return $this->jsonMsg('对不起，您的购买商品库存不足');
            }
            $allweight += $row['weight']*$postdata['goodsnum'][$key];
            $goodsprice += $row['productprice']*$postdata['goodsnum'][$key];
        }

        $dispatchprice = 0;
        $expressname = '';
        $dispatchid = 0;
        $expresssn = '';
        if($postdata['sendtype'] == 1){//快递方式
            //取出地址
            $address = ShopUserAddress::find()->select('concat(`name`,`province`,`city`,`county`,`address`,`tel`) as address')->where('id=:id',[':id'=>$postdata['address_id']])->asArray()->one();
            $address = $address['address'];
            //取出配送方式
            $dispatch = ShopDispatch::find()
                ->alias('s')
                ->select('se.express_name,s.*')
                ->leftJoin(ShopExpress::tableName().' as se','s.express=se.id')
                ->where('s.dispatchname=:dispachname',[':dispachname'=>$postdata['dispach']])
                ->asArray()
                ->one();
            $dispatchid = $dispatch['id'];
            $expressname = $dispatch['express_name'];
            //计算配送费用
            if ($allweight <= $dispatch['firstweight']) {
                $dispatchprice = $dispatch['firstprice'];
            } else {
                $dispatchprice = $dispatch['firstprice'];
                $secondweight = $allweight - $dispatch['firstweight'];
                if ($secondweight % $dispatch['secondweight'] == 0) {
                    $dispatchprice += (int)($secondweight / $dispatch['secondweight']) * $dispatch['secondprice'];
                } else {
                    $dispatchprice += (int)($secondweight / $dispatch['secondweight'] + 1) * $dispatch['secondprice'];
                }
            }
            $expresssn = date('Hiymd').$this->user['userid'].rand(10,99);
        }else{      //自提
            $address = $postdata['carrier_name'].'|'.$postdata['carrier_tel'];
            $since = ShopSinceAddress::find()->select('concat(`province`,`city`,`conty`,`area`) as address')->where('id=:id',[':id'=>$postdata['carrier_id']])->asArray()->one();
            $address .= $since['address'];
        }

        //积分省去的钱
        $scoreprice = 0;
        if(array_key_exists('usecredit',$postdata) && !empty($postdata['usecredit'])){
            $radio = SysSetting::getValue('scoretomoney');
            $user = BusinessUser::find()->select('score')->where('id=:id',[':id'=>$this->user['userid']])->asArray()->one();
            if($user['score'] <= $postdata['usecredit']){
                return $this->jsonMsg('对不起您的积分不足',1);
            }
            $scoreprice = intval($postdata['usecredit']*$radio);
        }


        //插入订单
        $data = [
            'address' => $address,
            'from_user' => $this->user['openid'],
            'userid' => $this->user['userid'],
            'sendtype' => $postdata['sendtype'],
            'paytype' => 1,     //默认微信支付
            'ordersn' => date('ymdHi').$this->user['userid'].rand(10,99),
            'remark' => $postdata['remark'],
            'goodsprice' => $goodsprice,
            'dispatch' => $dispatchid,
            'creditmoney' => $scoreprice,
            'price' => $goodsprice + $dispatchprice - $scoreprice,
            'dispatchprice' => $dispatchprice,
            'expresscom' => $expressname,
            'expresssn' => $expresssn,
            'createtime' => time(),
        ];

        \Yii::$app->db->createCommand()->insert(ShopOrder::tableName(),$data)->execute();

        $orderid = \Yii::$app->db->getLastInsertId();

        //插入order_goods
        foreach ($allgoods as $key => $row){
            $ogdata = [
                'goodsid' => $row['id'],
                'total' => $postdata['goodsnum'][$key],
                'price' => $row['productprice'],
                'orderid' => $orderid,
                'createtime' => time(),
            ];
            $res = \Yii::$app->db->createCommand()->insert(ShopOrderGoods::tableName(),$ogdata)->execute();
        }

        if($res){

            //发送模板消息
            $titles = ArrayHelper::getColumn($allgoods,'title');
            $titles  = implode(',',$titles);
            $data = [
                "first"  => "恭喜您购买的“".$titles."”下单成功，",
                "keyword1"   => "下单成功",
                "keyword2"  => date('Y-m-d H:i:s'),
                "remark" => "欢迎再次光临！",
            ];
            $notice = \Yii::$app->wechat->notice->to($this->user['openid'])
                ->url(\Yii::$app->request->hostInfo.'/business/user/pork-order/index?status=0')
                ->template(SysSetting::getValue('template_msgid'))
                ->andData($data)
                ->send();

            return $this->jsonMsg('下单成功',0,['url'=>Url::to(['/pay/wechat/pay/index','oid'=>$orderid])]);
        }else{
            return $this->jsonMsg('下单失败',1);
        }

    }


    /**
     * 领养下单
     */
    public function actionRasingPrePay()
    {
        $postdata = \Yii::$app->request->post();
        if(!key_exists('xieyi',$postdata) || $postdata['xieyi'] != 'on'){
            return $this->jsonMsg('请阅读并同意认养协议',1);
        }

//        手机验证手机短信码
        if(\Yii::$app->session->get('smscode') != $postdata['code']){
            return $this->jsonMsg('短信验证码错误',1);
        }



        $pig = BusinessPig::find()->alias('p')->select('p.id,p.no,p.price,v.title,lingperson')->leftJoin(BusinessVariety::tableName().' as v','p.varietyid=v.id')->where('p.id=:id',[':id'=>$postdata['pigid']])->asArray()->one();

        if($pig['price'] <= 0){
            return $this->jsonMsg('该仔猪价格待估，暂时不能购买',1);
        }
        if($pig['lingperson'] != 0){
            return $this->jsonMsg('该仔猪已被认养，您可以选择其他仔猪进行认养',1);
        }

        $data = [
            'pigid' => $pig['id'],
            'pigno' => $pig['no'],
            'pigprice' => $pig['price'],
            'pigvariety' => $pig['title'],
            'price' => $pig['price'],
            'createtime' => time(),
            'name' => $postdata['name'],
            'phone' => $postdata['tel'],
            'remark' => $postdata['remark'],
            'ordersn' => date('ymdHi').$this->user['userid'].rand(10,99),
            'userid' => $this->user['userid'],
            'address' => $postdata['address'],
            'wanttime' => strtotime($postdata['wanttime']),
        ];

        $res = \Yii::$app->db->createCommand()->insert(ShopRaisingOrder::tableName(),$data)->execute();
        $orderid = \Yii::$app->db->getLastInsertID();
        if($res){

            $data = [
                "first"  => "恭喜您领养编号为“".$pig['no']."”的仔猪下单成功，",
                "keyword1"   => "下单成功",
                "keyword2"  => date('Y-m-d H:i:s'),
                "remark" => "欢迎再次光临！",
            ];
            $notice = \Yii::$app->wechat->notice->to($this->user['openid'])
                ->url(\Yii::$app->request->hostInfo.'/business/user/my-pigs')
                ->template(SysSetting::getValue('template_msgid'))
                ->andData($data)
                ->send();

            return $this->jsonMsg('下单成功',0,['url'=>Url::to(['/pay/wechat/pay/rasing','oid'=>$orderid])]);
        }else{
            return $this->jsonMsg('下单失败',1);
        }


    }










}